package cfca.paperless.client.servlet._2_extend._2_05_VerifyPkcs;

import java.io.File;
import java.io.FileInputStream;
import java.security.PrivateKey;
import java.util.Date;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.StringUtil;
import cfca.sadk.algorithm.common.Mechanism;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.util.KeyUtil;
import cfca.sadk.util.Signature;
import cfca.sadk.x509.certificate.X509Cert;

public class VerifyPkcsTest01 {

    /**
     * 验签接口
     * 
     * @param args
     * @throws IOException
     * @throws
     */
    public static void main(String[] args) throws Exception {
        try {
            long timeStart = System.currentTimeMillis();// 开始时间

            // 初始化客户端对象
            PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.extUrl, 10000, 60000);// 无纸化辅助接口的访问URL

            //公钥证书
            byte[] x509Cert = FileUtils.readFileToByteArray(new File("./TestData/cert/11111111.cer"));
            X509Cert cert = new X509Cert(x509Cert);
            //私钥
            PrivateKey privateKey = KeyUtil.getPrivateKeyFromPFX(new FileInputStream("./TestData/cert/11111111.pfx"), "11111111");
            
            JCrypto.getInstance().initialize(JCrypto.JSOFT_LIB, null);
            cfca.sadk.lib.crypto.Session mySession = JCrypto.getInstance().openSession(JCrypto.JSOFT_LIB);
            Signature sigUtil = new Signature();
            
            byte[] sourceData = "11111111".getBytes();
            byte[] signature = sigUtil.p7SignMessageDetach(Mechanism.SHA1_RSA, sourceData, privateKey, new X509Cert(x509Cert), mySession);
            //System.out.println("signature:" + new String(signature));
            
            String verifyPkcsBeanXml = PaperlessUtil.buildVerifyPkcsXml((signature), "2", sourceData);
            // 操作员编码或者机构号
            String operatorCode = PaperlessConfig.operatorCode;
            // 渠道编码，可以为空
            String channelCode = PaperlessConfig.channelCode;

            System.out.println(verifyPkcsBeanXml);
            
            String returnMessage = clientBean.verifyPkcs(verifyPkcsBeanXml, operatorCode, channelCode);

            String code = StringUtil.getNodeText(returnMessage, "Code");
            if ("200".equals(code)) {
                System.out.println("verifyPkcs ok!!");
            } else {
                System.out.println("verifyPkcs error!!");
                System.out.println(returnMessage);
            }
            long timeEnd = System.currentTimeMillis();// 结束时间
            System.out.println("time:" + (timeEnd - timeStart));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
